import pyodbc
from config import config


def execute_query(query_string):
    # 创建连接对象
    conn = pyodbc.connect(config.connection_string)

    # 创建游标对象
    cursor = conn.cursor()

    # 执行查询
    cursor.execute(query_string)

    # 获取查询结果的列名
    columns = [column[0] for column in cursor.description]

    # 获取查询结果的所有行数据
    rows = cursor.fetchall()

    # 将查询结果转换成列表，每行数据作为一个字典
    result_set = [dict(zip(columns, row)) for row in rows]

    # 关闭游标和连接
    cursor.close()
    conn.close()

    # 返回查询结果
    return result_set


def execute_sql(sql_query):
    try:
        # 连接到数据库
        conn = pyodbc.connect(config.connection_string)
        cursor = conn.cursor()

        # 执行 SQL 语句
        cursor.execute(sql_query)
        row_count = cursor.rowcount

        # 提交事务并关闭连接
        conn.commit()
        conn.close()

        # 返回受影响的行数
        return row_count

    except pyodbc.Error as e:
        print(f"Error executing SQL query: {sql_query}")
        print(e)
        return None
